package com.trinity.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import com.trinity.common.constant.Constants;
import com.trinity.common.core.controller.BaseController;
import com.trinity.common.core.domain.AjaxResult;
import com.trinity.common.core.domain.entity.WxUser;
import com.trinity.common.utils.StringUtils;
import com.trinity.service.IWxUserService;
import com.trinity.utils.JsonUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

//import static java.awt.SystemColor.info;

/**
 * 微信小程序用户接口
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@RestController
@AllArgsConstructor
@Slf4j
@RequestMapping("/wx/user/{appid}")
public class WxMaUserController extends BaseController {
    private final WxMaService wxMaService;
    @Resource
    private IWxUserService wxUserService;

    /**
     * 登陆接口
     */

    @GetMapping("/login")
    public AjaxResult login(@PathVariable String appid, String code, String phone) {

        if (StringUtils.isBlank(code)) {
            return error("empty jscode");
        }

        if (!wxMaService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }
        WxMaJscode2SessionResult session = wxUserService.getSession(appid, code);
        log.info(session.toString());
        if (!StringUtils.isBlank(phone)) {
//            Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
            // 判断用户是否存在
            boolean isCreated = wxUserService.checkUserByPhone(phone);

            if (isCreated) {
                // 判断用户是否已经绑定
                boolean isBundled = wxUserService.checkPhoneIsBundled(phone);
                if (!isBundled) {
                    AjaxResult ajax = AjaxResult.success();
                    // 生成令牌
                    wxUserService.bundledWxUser(phone, session.getOpenid());
                    String token = wxUserService.createToken(session.getOpenid(), session.getSessionKey());
                    ajax.put(Constants.TOKEN, token);
                    return ajax;
                } else {
                    return error("该用户已经绑定");
                }
            } else {
                return error("用户不存在");
            }
        } else {
            WxUser wxUser = wxUserService.selectWxUserByOpenId(session.getOpenid());
            if (StringUtils.isNotNull(wxUser)) {
                // 生成令牌
                AjaxResult ajax = AjaxResult.success();
                String token = wxUserService.createToken(session.getOpenid(), session.getSessionKey());
                ajax.put(Constants.TOKEN, token);
                return ajax;
            } else {
                return error("用户未绑定");
            }

        }


    }

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @GetMapping("/info")
    public String info(@PathVariable String appid, String sessionKey,
                       String signature, String rawData, String encryptedData, String iv) {


        if (!wxMaService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        // 用户信息校验
        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            WxMaConfigHolder.remove();//清理ThreadLocal
            return "user check failed";
        }

        // 解密用户信息
        WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
        WxMaConfigHolder.remove();//清理ThreadLocal
        return JsonUtils.toJson(userInfo);
    }

    /**
     * <pre>
     * 获取用户绑定手机号信息
     * </pre>
     */
    @GetMapping("/phone")
    public String phone(@PathVariable String appid, String sessionKey, String signature,
                        String rawData, String encryptedData, String iv) {
        if (!wxMaService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        // 用户信息校验
        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            WxMaConfigHolder.remove();//清理ThreadLocal
            return "user check failed";
        }

        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
        WxMaConfigHolder.remove();//清理ThreadLocal
        return JsonUtils.toJson(phoneNoInfo);
    }

}
